<template>
  <div class="app-container">
    <!-- 使用按钮组替代Tabs -->
    <el-card class="tab-header-card">
      <div class="tab-buttons">
        <el-button :type="activeTab === 'month' ? 'primary' : ''" @click="activeTab = 'month'" size="large">
          <el-icon>
            <Calendar />
          </el-icon> 月视图
        </el-button>
        <el-button :type="activeTab === 'week' ? 'primary' : ''" @click="weekChange" size="large">
          <el-icon>
            <Calendar />
          </el-icon> 周视图
        </el-button>
      </div>
    </el-card>

    <!-- 月视图 -->
    <div v-if="activeTab === 'month'" class="tab-content">
      <el-card class="calendar-card">
        <!-- 操作区域 -->
        <el-row :gutter="20" justify="space-between" align="middle">
          <el-col :span="12">
            <el-date-picker v-model="monthDate" type="month" placeholder="选择月份" value-format="YYYY-MM"
              @change="fetchMonthViewData" style="width: 200px" />
            <el-button-group style="margin-left: 20px;">
              <el-button @click="prevMonth">
                <el-icon>
                  <ArrowLeft />
                </el-icon>上个月
              </el-button>
              <el-button @click="nextMonth">
                下个月<el-icon>
                  <ArrowRight />
                </el-icon>
              </el-button>
              <el-button type="primary" @click="goToToday">
                今天
              </el-button>
            </el-button-group>
          </el-col>
          <el-col :span="12" class="text-right">
            <el-button type="primary" @click="showCreateDialog">
              <el-icon>
                <Plus />
              </el-icon>新增排班
            </el-button>
            <el-button type="success" @click="showOneClickDialog">
              <el-icon>
                <MagicStick />
              </el-icon>一键排班
            </el-button>
            <!-- <el-button type="warning" @click="handleExport">
              <el-icon><Download /></el-icon>导出数据
            </el-button> -->
          </el-col>
        </el-row>
        <!-- 月视图日历 -->
        <div class="calendar-header mt-2">
          <div class="calendar-weekday" v-for="day in weekDays" :key="day">{{ day }}</div>
        </div>
        <div class="calendar-body">
          <div v-for="(week, weekIndex) in monthWeeks" :key="weekIndex" class="calendar-week">
            <div v-for="day in week" :key="day.date" class="calendar-day" :class="{
              'current-month': day.isCurrentMonth,
              'today': day.isToday,
              'has-data': day.rosterData && day.rosterData.length > 0
            }" @click="handleDayClick(day)">
              <div class="day-header">
                <span class="day-number">{{ day.day }}</span>
                <span v-if="day.isToday" class="today-badge">今</span>
                <div class="day-actions" v-if="day.isCurrentMonth">
                  <el-button size="mini" type="primary" link @click.stop="handleAddForDay(day)" title="新增排班">
                    <el-icon>
                      <Plus />
                    </el-icon>
                  </el-button>
                </div>
              </div>
              <div class="day-content">
                <div v-for="roster in day.rosterData" :key="roster.id" class="roster-item"
                  @click.stop="handleRosterClick(roster, day)">
                  <el-tag size="small" :type="getRosterTagType(roster.sourceType)" class="roster-tag" closable
                    @close="handleDeleteRoster(roster.id, $event)">
                    {{ roster.personName }} - {{ roster.shiftName }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 周视图 -->
    <div v-else class="tab-content">
      <!-- 周视图信息 -->
      <el-card class="mt-2">
         <el-row :gutter="20" justify="space-between" align="middle">
          <el-col :span="12">
            <div class="week-selector">
              <el-button @click="handlePrevWeek" :disabled="loading">
                <el-icon>
                  <ArrowLeft />
                </el-icon>上一周
              </el-button>
              <el-date-picker v-model="weekDate" type="date" placeholder="选择周开始日期" value-format="YYYY-MM-DD"
                @change="fetchWeekViewData" style="width: 200px; margin: 0 10px" />
              <el-button @click="handleNextWeek" :disabled="loading">
                下一周<el-icon>
                  <ArrowRight />
                </el-icon>
              </el-button>
              <el-button @click="goToCurrentWeek" style="margin-left: 10px">
                本周
              </el-button>
            </div>
          </el-col>
          <el-col :span="12" class="text-right">
            <el-button type="primary" @click="showCreateDialog">
              <el-icon>
                <Plus />
              </el-icon>新增排班
            </el-button>
            <!-- <el-button type="warning" @click="handleExport">
              <el-icon>
                <Download />
              </el-icon>导出数据
            </el-button> -->
          </el-col>
        </el-row>
        <!-- <div class="week-header-info mt-2">
          <h3>{{ weekDisplayText }}</h3>
          <p class="week-date-range">{{ weekDateRange }}</p>
        </div> -->

        <!-- 周视图日历 -->
        <div class="week-calendar mt-2">
          <div class="week-calendar-header">
            <div class="week-day-header" v-for="(dayName, index) in weekDays" :key="dayName">
              <div class="week-day-name">{{ dayName }}</div>
              <div class="week-date">{{ getWeekDateDisplay(index) }}</div>
            </div>
          </div>

          <div class="week-calendar-body">
            <div class="week-day-column" v-for="(date, index) in weekDates" :key="date">
              <div class="week-day-cell" :class="{
                'today': isToday(date),
                'weekend': isWeekend(index)
              }">
                <div class="day-header">
                  <span class="day-number">{{ new Date(date).getDate() }}</span>
                  <span v-if="isToday(date)" class="today-badge">今</span>
                </div>
                <div class="day-roster-list">
                  <div v-for="roster in getRosterDataByDate(date)" :key="roster.id" class="roster-card"
                    @click="handleRosterClick(getRosterDataByDate(date), { date: date })">
                    <div class="roster-time">{{ roster.startAt }} - {{ roster.endAt }}</div>
                    <div class="roster-person">{{ roster.personName }}</div>
                    <div class="roster-shift">
                      <el-tag size="small" :type="getRosterTagType(roster.sourceType)">
                        {{ roster.shiftName }}
                      </el-tag>
                    </div>
                    <div class="roster-actions">
                      <el-button size="mini" link type="primary" @click.stop="handleEditRoster(roster)">
                        <el-icon>
                          <Edit />
                        </el-icon>
                      </el-button>
                      <el-button size="mini" link type="danger" @click.stop="handleDeleteRoster(roster.id)">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </el-button>
                    </div>
                  </div>
                  <div v-if="getRosterDataByDate(date).length === 0" class="no-data">
                    <span class="no-data-text">暂无排班</span>
                    <el-button size="mini" link type="primary" @click="handleAddForDayInWeek(date)">
                      <el-icon>
                        <Plus />
                      </el-icon>新增
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      </el-card>
    </div>

    <!-- 排班详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="`${selectedDate} 排班详情`" width="70%">
      <div class="schedule-detail">
        <div class="detail-header">
          <h3>排班详情</h3>
          <el-button type="primary" @click="handleAddForSelectedDate">
            <el-icon>
              <Plus />
            </el-icon>新增排班
          </el-button>
        </div>

        <el-table :data="selectedDayRosters" border style="width: 100%; margin-top: 20px;">
          <el-table-column prop="personName" label="人员" align="center" />
          <el-table-column prop="shiftName" label="班次" align="center">
            <template #default="{ row }">
              <el-tag :type="getShiftType(row.shiftName)" effect="dark">
                {{ row.shiftName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="startAt" label="开始时间" align="center" />
          <el-table-column prop="endAt" label="结束时间" align="center" />
          <el-table-column label="工作时长" align="center">
            <template #default="{ row }">
              {{ calculateDuration(row.startAt, row.endAt) }}
            </template>
          </el-table-column>
          <el-table-column label="来源" align="center">
            <template #default="{ row }">
              <el-tag :type="getRosterTagType(row.sourceType)">
                {{ getSourceTypeLabel(row.sourceType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEditRoster(row)">编辑</el-button>
              <el-button link type="danger" @click="handleDeleteRoster(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑排班对话框 -->
    <el-dialog v-model="createDialogVisible" :title="dialogTitle" width="600px" :close-on-click-modal="false">
      <el-form :model="rosterForm" :rules="rosterRules" ref="rosterFormRef" label-width="100px">
        <el-form-item label="排班日期" prop="rosterDate">
          <el-date-picker v-model="rosterForm.rosterDate" type="date" placeholder="选择日期" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" style="width: 100%" :disabled="isEditing" />
        </el-form-item>
        <el-form-item label="人员" prop="personId">
          <el-select v-model="rosterForm.personId" placeholder="选择人员" style="width: 100%">
            <el-option v-for="person in personList" :key="person.id" :label="person.fullName" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="班次" prop="shiftId">
          <el-select v-model="rosterForm.shiftId" placeholder="选择班次" style="width: 100%" @change="handleShiftChange">
            <el-option v-for="shift in classesList" :key="shift.departmentId" :label="shift.classesName"
              :value="shift.departmentId" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startAt">
          <el-time-picker v-model="rosterForm.startAt" placeholder="开始时间" format="HH:mm:ss" value-format="HH:mm:ss"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endAt">
          <el-time-picker v-model="rosterForm.endAt" placeholder="结束时间" format="HH:mm:ss" value-format="HH:mm:ss"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="来源" prop="sourceType">
          <el-select v-model="rosterForm.sourceType" placeholder="选择来源" style="width: 100%">
            <el-option label="手工" :value="1" />
            <el-option label="模板生成" :value="2" />
            <el-option label="导入" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="rosterForm.remark" type="textarea" :rows="3" placeholder="可填写备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRosterForm" :loading="submitLoading">
          {{ isEditing ? '更新' : '确认' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 一键排班对话框 -->
    <el-dialog v-model="oneClickDialogVisible" title="一键排班" width="500px" :close-on-click-modal="false">
      <el-form :model="oneClickForm" :rules="oneClickRules" ref="oneClickFormRef" label-width="100px">
        <el-form-item label="月份" prop="month">
          <el-date-picker v-model="oneClickForm.month" type="month" placeholder="选择月份" value-format="YYYY-MM"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="排班人员" prop="personId">
          <el-select v-model="oneClickForm.personId" placeholder="选择人员" style="width: 100%">
            <el-option v-for="person in personList" :key="person.id" :label="person.fullName" :value="person.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="周期模板" prop="cycleId">
          <el-select v-model="oneClickForm.cycleId" placeholder="选择周期模板" style="width: 100%">
            <el-option v-for="cycle in cycleList" :key="cycle.id" :label="cycle.cycleName" :value="cycle.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="oneClickDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitOneClickRoster" :loading="submitLoading">开始排班</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Edit,
  Delete,
  Refresh,
  MagicStick,
  ArrowLeft,
  ArrowRight,
} from '@element-plus/icons-vue'

// 导入API
import {
  getMonthViewData,
  getWeekViewData,
  getPersonList,
  getClassesList,
  getCycleList,
  addRosterRecord,
  updateRosterRecord,
  deleteRosterRecord,
  oneClickRoster,
  exportRosterRecord,
  getRosterRecordDetail
} from '@/api/dispatch/affair/schedule_calendar'

// 响应式数据
const activeTab = ref('month')
const monthDate = ref(new Date().toISOString().slice(0, 7)) // YYYY-MM
const weekDate = ref(new Date().toISOString().slice(0, 10)) // YYYY-MM-DD
const loading = ref(false)
const submitLoading = ref(false)

// 数据相关
const monthViewData = ref([])
const weekViewData = ref([])
const personList = ref([])
const classesList = ref([])
const cycleList = ref([])
const selectedDayRosters = ref([])

// 分页相关
const weekPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const detailDialogVisible = ref(false)
const createDialogVisible = ref(false)
const oneClickDialogVisible = ref(false)
const selectedDate = ref('')
const dialogTitle = ref('新增排班')
const isEditing = ref(false)
const editingRosterId = ref(null)

// 星期数组
const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 表单相关
const rosterFormRef = ref(null)
const oneClickFormRef = ref(null)
const rosterForm = reactive({
  personId: '',
  shiftId: '',
  rosterDate: new Date().toISOString().slice(0, 10),
  startAt: '08:00:00',
  endAt: '17:00:00',
  sourceType: 1,
  remark: ''
})

const oneClickForm = reactive({
  month: monthDate.value,
  personId: '',
  cycleId: ''
})

const rosterRules = {
  rosterDate: [{ required: true, message: '请选择排班日期', trigger: 'change' }],
  personId: [{ required: true, message: '请选择人员', trigger: 'change' }],
  shiftId: [{ required: true, message: '请选择班次', trigger: 'change' }],
  startAt: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endAt: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  sourceType: [{ required: true, message: '请选择来源类型', trigger: 'change' }]
}

const oneClickRules = {
  month: [{ required: true, message: '请选择月份', trigger: 'change' }],
  personId: [{ required: true, message: '请选择人员', trigger: 'change' }],
  cycleId: [{ required: true, message: '请选择周期模板', trigger: 'change' }]
}

// 计算属性
const monthWeeks = computed(() => {
  if (!monthDate.value) return []

  const [year, month] = monthDate.value.split('-').map(Number)
  const firstDay = new Date(year, month - 1, 1)
  const lastDay = new Date(year, month, 0)
  const daysInMonth = lastDay.getDate()

  const firstDayOfWeek = firstDay.getDay()
  const weeks = []
  let currentWeek = []

  // 添加上个月的最后几天
  const prevMonthLastDay = new Date(year, month - 1, 0).getDate()
  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    const day = prevMonthLastDay - i
    const prevMonth = month === 1 ? 12 : month - 1
    const prevYear = month === 1 ? year - 1 : year
    const dateStr = `${prevYear}-${String(prevMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`

    currentWeek.push({
      day,
      date: dateStr,
      isCurrentMonth: false,
      isToday: false,
      rosterData: getRosterDataByDate(dateStr)
    })
  }

  // 添加当月的天数
  for (let day = 1; day <= daysInMonth; day++) {
    const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
    const isToday = dateStr === new Date().toISOString().slice(0, 10)

    currentWeek.push({
      day,
      date: dateStr,
      isCurrentMonth: true,
      isToday,
      rosterData: getRosterDataByDate(dateStr)
    })

    if (currentWeek.length === 7) {
      weeks.push([...currentWeek])
      currentWeek = []
    }
  }

  // 添加下个月的前几天
  if (currentWeek.length > 0) {
    let nextMonthDay = 1
    while (currentWeek.length < 7) {
      const nextMonth = month === 12 ? 1 : month + 1
      const nextYear = month === 12 ? year + 1 : year
      const dateStr = `${nextYear}-${String(nextMonth).padStart(2, '0')}-${String(nextMonthDay).padStart(2, '0')}`

      currentWeek.push({
        day: nextMonthDay,
        date: dateStr,
        isCurrentMonth: false,
        isToday: false,
        rosterData: getRosterDataByDate(dateStr)
      })
      nextMonthDay++
    }
    weeks.push(currentWeek)
  }

  return weeks
})

const weekChange = () => {
  activeTab.value = 'week';
  goToCurrentWeek();
}
const weekDates = computed(() => {
  if (!weekDate.value) return []

  const date = new Date(weekDate.value)
  const dayOfWeek = date.getDay()
  const startDate = new Date(date)
  startDate.setDate(date.getDate() - dayOfWeek)

  const dates = []
  for (let i = 0; i < 7; i++) {
    const currentDate = new Date(startDate)
    currentDate.setDate(startDate.getDate() + i)
    dates.push(currentDate.toISOString().slice(0, 10))
  }

  return dates
})

const weekDateRange = computed(() => {
  const { startDate, endDate } = getWeekStartEnd(weekDate.value)
  return `${startDate} 至 ${endDate}`
})

const weekDisplayText = computed(() => {
  const date = new Date(weekDate.value)
  const year = date.getFullYear()
  const weekNumber = getWeekNumber(date)
  return `${year}年 第${weekNumber}周`
})

// 工具函数
const getWeekStartEnd = (dateString) => {
  const date = new Date(dateString)
  const dayOfWeek = date.getDay()
  const startDate = new Date(date)
  startDate.setDate(date.getDate() - dayOfWeek)
  const endDate = new Date(startDate)
  endDate.setDate(startDate.getDate() + 6)

  return {
    startDate: startDate.toISOString().slice(0, 10),
    endDate: endDate.toISOString().slice(0, 10)
  }
}

const getWeekNumber = (date) => {
  const firstDayOfYear = new Date(date.getFullYear(), 0, 1)
  const pastDaysOfYear = (date - firstDayOfYear) / 86400000
  return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7)
}

const getRosterDataByDate = (date) => {
  const data = activeTab.value === 'month' ? monthViewData.value : weekViewData.value
  return data.filter(item => item.rosterDate === date) || []
}

const getShiftType = (shiftName) => {
  const map = {
    '早班': 'success',
    '中班': 'warning',
    '晚班': 'danger'
  }
  return map[shiftName] || 'info'
}

const getRosterTagType = (sourceType) => {
  const types = { 1: 'primary', 2: 'success', 3: 'warning' }
  return types[sourceType] || 'info'
}

const getSourceTypeLabel = (sourceType) => {
  const types = { 1: '手工', 2: '模板生成', 3: '导入' }
  return types[sourceType] || '未知'
}

const calculateDuration = (startTime, endTime) => {
  if (!startTime || !endTime) return '--'

  const start = new Date(`2000-01-01 ${startTime}`)
  const end = new Date(`2000-01-01 ${endTime}`)
  let duration = (end - start) / (1000 * 60 * 60) // 小时

  if (duration < 0) duration += 24 // 处理跨天情况

  return `${Math.round(duration * 10) / 10}小时`
}

const getWeekDateDisplay = (index) => {
  if (weekDates.value[index]) {
    return weekDates.value[index].slice(5) // 显示 MM-DD
  }
  return ''
}

const isToday = (date) => {
  return date === new Date().toISOString().slice(0, 10)
}

const isWeekend = (index) => {
  return index === 0 || index === 6 // 周日或周六
}

// API调用
const fetchMonthViewData = async () => {
  try {
    loading.value = true
    const { data } = await getMonthViewData({
      yearMonth: monthDate.value
    })
    monthViewData.value = data || []
  } catch (error) {
    console.error('获取月视图数据失败:', error)
    ElMessage.error('获取月视图数据失败')
  } finally {
    loading.value = false
  }
}

const fetchWeekViewData = async () => {
  const { startDate, endDate } = getWeekStartEnd(weekDate.value)

  const params = {
    weekStartTime: startDate,
    weekEndTime: endDate,
    pageNum: weekPagination.currentPage,
    pageSize: weekPagination.pageSize
  }

  const { data } = await getWeekViewData(params)
  weekViewData.value = data || []
}

const fetchPersonList = async () => {
  try {
    const { data } = await getPersonList()
    personList.value = data || []
  } catch (error) {
    console.error('获取人员列表失败:', error)
    ElMessage.error('获取人员列表失败')
  }
}

const fetchClassesList = async () => {
  try {
    const { data } = await getClassesList()
    classesList.value = data || []
  } catch (error) {
    console.error('获取班次列表失败:', error)
    ElMessage.error('获取班次列表失败')
  }
}

const fetchCycleList = async () => {
  try {
    const data = await getCycleList()
    cycleList.value = data.rows || []
  } catch (error) {
    console.error('获取周期模板列表失败:', error)
    ElMessage.error('获取周期模板列表失败')
  }
}

// 事件处理
const handleTabChange = () => {
  if (activeTab.value === 'month') {
    fetchMonthViewData()
  } else {
    fetchWeekViewData()
  }
}

const prevMonth = () => {
  const [year, month] = monthDate.value.split('-').map(Number)
  const newMonth = month === 1 ? 12 : month - 1
  const newYear = month === 1 ? year - 1 : year
  monthDate.value = `${newYear}-${String(newMonth).padStart(2, '0')}`
  fetchMonthViewData()
}

const nextMonth = () => {
  const [year, month] = monthDate.value.split('-').map(Number)
  const newMonth = month === 12 ? 1 : month + 1
  const newYear = month === 12 ? year + 1 : year
  monthDate.value = `${newYear}-${String(newMonth).padStart(2, '0')}`
  fetchMonthViewData()
}

const goToToday = () => {
  monthDate.value = new Date().toISOString().slice(0, 7)
  fetchMonthViewData()
}

const handlePrevWeek = () => {
  const date = new Date(weekDate.value)
  date.setDate(date.getDate() - 7)
  weekDate.value = date.toISOString().slice(0, 10)
  fetchWeekViewData()
}

const handleNextWeek = () => {
  const date = new Date(weekDate.value)
  date.setDate(date.getDate() + 7)
  weekDate.value = date.toISOString().slice(0, 10)
  fetchWeekViewData()
}

const goToCurrentWeek = () => {
  weekDate.value = new Date().toISOString().slice(0, 10)
  fetchWeekViewData()
}

const handleDayClick = (day) => {
  if (day.isCurrentMonth) {
    selectedDate.value = day.date
    selectedDayRosters.value = day.rosterData || []
    detailDialogVisible.value = true
  }
}

const handleRosterClick = (roster, day) => {

  selectedDate.value = day.date
  selectedDayRosters.value = [...roster]
  detailDialogVisible.value = true
}

const handleAddForDay = (day) => {
  resetRosterForm()
  rosterForm.rosterDate = day.date
  dialogTitle.value = `新增排班 - ${day.date}`
  isEditing.value = false
  createDialogVisible.value = true
}

const handleAddForDayInWeek = (date) => {
  resetRosterForm()
  rosterForm.rosterDate = date
  dialogTitle.value = `新增排班 - ${date}`
  isEditing.value = false
  createDialogVisible.value = true
}

const handleAddForSelectedDate = () => {
  resetRosterForm()
  rosterForm.rosterDate = selectedDate.value
  dialogTitle.value = `新增排班 - ${selectedDate.value}`
  isEditing.value = false
  createDialogVisible.value = true
  detailDialogVisible.value = false
}

const handleEditRoster = async (roster) => {
  try {
    const { data } = await getRosterRecordDetail(roster.id)
    if (data) {
      Object.assign(rosterForm, data)
      dialogTitle.value = `编辑排班 - ${data.rosterDate}`
      isEditing.value = true
      editingRosterId.value = data.id
      createDialogVisible.value = true
      detailDialogVisible.value = false
    }
  } catch (error) {
    console.error('获取排班详情失败:', error)
    ElMessage.error('获取排班详情失败')
  }
}

const handleDeleteRoster = async (id, event = null) => {
  if (event) {
    event.stopPropagation()
  }

  try {
    await ElMessageBox.confirm('确认删除该排班记录吗?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteRosterRecord(id)
    ElMessage.success('删除成功')

    // 刷新数据
    if (activeTab.value === 'month') {
      fetchMonthViewData()
    } else {
      fetchWeekViewData()
    }

    // 如果是在详情对话框中删除，刷新详情数据
    if (detailDialogVisible.value) {
      selectedDayRosters.value = selectedDayRosters.value.filter(item => item.id !== id)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const showCreateDialog = () => {
  resetRosterForm()
  dialogTitle.value = '新增排班'
  isEditing.value = false
  createDialogVisible.value = true
}

const showOneClickDialog = () => {
  oneClickForm.month = monthDate.value
  oneClickDialogVisible.value = true
}

const resetRosterForm = () => {
  Object.keys(rosterForm).forEach(key => {
    if (key !== 'sourceType') {
      rosterForm[key] = ''
    }
  })
  rosterForm.rosterDate = new Date().toISOString().slice(0, 10)
  rosterForm.startAt = '08:00:00'
  rosterForm.endAt = '17:00:00'
  rosterForm.sourceType = 1
  editingRosterId.value = null
}

const submitRosterForm = async () => {
  if (!rosterFormRef.value) return

  try {
    await rosterFormRef.value.validate()

    submitLoading.value = true
    if (isEditing.value) {
      await updateRosterRecord({
        ...rosterForm,
        id: editingRosterId.value
      })
      ElMessage.success('更新成功')
    } else {
      await addRosterRecord(rosterForm)
      ElMessage.success('新增成功')
    }

    createDialogVisible.value = false

    // 刷新数据
    if (activeTab.value === 'month') {
      fetchMonthViewData()
    } else {
      fetchWeekViewData()
    }

    // 刷新详情对话框数据
    if (detailDialogVisible.value) {
      selectedDayRosters.value = getRosterDataByDate(selectedDate.value)
    }
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data.msg || '操作失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const submitOneClickRoster = async () => {
  if (!oneClickFormRef.value) return

  try {
    await oneClickFormRef.value.validate()

    submitLoading.value = true
    await oneClickRoster(oneClickForm)

    ElMessage.success('一键排班成功')
    oneClickDialogVisible.value = false
    fetchMonthViewData()
  } catch (error) {
    console.error('一键排班失败:', error)
    if (error.response) {
      ElMessage.error(error.response.data.msg || '一键排班失败')
    }
  } finally {
    submitLoading.value = false
  }
}

const handleShiftChange = (value) => {
  const item = classesList.value.find(item => item.departmentId == value)
  if (item) {
    rosterForm.startAt = item.classesTime
    rosterForm.endAt = item.endTime
  }
}

const handleExport = async () => {
  try {
    let params = {}

    if (activeTab.value === 'month') {
      params = { yearMonth: monthDate.value }
    } else {
      const { startDate, endDate } = getWeekStartEnd(weekDate.value)
      params = { weekStartTime: startDate, weekEndTime: endDate }
    }

    const response = await exportRosterRecord(params)

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    const filename = activeTab.value === 'month'
      ? `排班数据_${monthDate.value}.xlsx`
      : `排班数据_${weekDate.value}.xlsx`
    link.setAttribute('download', filename)
    document.body.appendChild(link)
    link.click()
    link.remove()

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

const handleWeekSizeChange = (val) => {
  weekPagination.pageSize = val
  weekPagination.currentPage = 1
  fetchWeekViewData()
}

const handleWeekCurrentChange = (val) => {
  weekPagination.currentPage = val
  fetchWeekViewData()
}

onMounted(() => {
  fetchPersonList()
  fetchClassesList()
  fetchCycleList()
  fetchMonthViewData()
})
</script>

<style scoped>
.tab-header-card {
  margin-bottom: 20px;
}

.tab-buttons {
  display: flex;
  gap: 10px;
}

.text-right {
  text-align: right;
}

.week-selector {
  display: inline-flex;
  align-items: center;
}

.week-header-info {
  text-align: center;
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.week-header-info h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.week-date-range {
  margin: 5px 0 0 0;
  color: #606266;
  font-size: 14px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
  color: #303133;
}

/* 月视图日历样式 */
.calendar-card {
  width: 100%;
}

.calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.calendar-weekday {
  padding: 12px;
  text-align: center;
  font-weight: bold;
  color: #606266;
}

.calendar-body {
  min-height: 500px;
}

.calendar-week {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  border-bottom: 1px solid #e4e7ed;
}

.calendar-day {
  min-height: 100px;
  padding: 8px;
  border-right: 1px solid #e4e7ed;
  cursor: pointer;
  transition: background-color 0.3s;
}

.calendar-day:last-child {
  border-right: none;
}

.calendar-day:hover {
  background-color: #f5f7fa;
}

.calendar-day.current-month {
  background-color: white;
}

.calendar-day:not(.current-month) {
  background-color: #fafafa;
  color: #c0c4cc;
}

.calendar-day.today {
  background-color: #ecf5ff;
}

.calendar-day.has-data {
  background-color: #f0f9ff;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.day-number {
  font-size: 14px;
  font-weight: bold;
}

.today-badge {
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.day-actions {
  display: flex;
  gap: 2px;
}

.day-content {
  max-height: 60px;
  overflow-y: auto;
}

.roster-item {
  margin-bottom: 2px;
}

.roster-tag {
  width: 100%;
  justify-content: center;
  margin-bottom: 2px;
}

/* 周视图日历样式 */
.week-calendar {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 20px;
}

.week-calendar-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.week-day-header {
  padding: 12px;
  text-align: center;
  border-right: 1px solid #e4e7ed;
}

.week-day-header:last-child {
  border-right: none;
}

.week-day-name {
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.week-date {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.week-calendar-body {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  min-height: 400px;
}

.week-day-column {
  border-right: 1px solid #e4e7ed;
  min-height: 400px;
}

.week-day-column:last-child {
  border-right: none;
}

.week-day-cell {
  height: 100%;
  padding: 8px;
  background-color: white;
  transition: background-color 0.3s;
}

.week-day-cell.today {
  background-color: #ecf5ff;
}

.week-day-cell.weekend {
  background-color: #fafafa;
}

.week-day-cell:hover {
  background-color: #f5f7fa;
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.day-number {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.today-badge {
  background-color: #409eff;
  color: white;
  border-radius: 4px;
  padding: 2px 6px;
  font-size: 12px;
}

.day-roster-list {
  max-height: 550px;
  overflow-y: auto;
}

.roster-card {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.roster-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  transform: translateY(-1px);
}

.roster-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.roster-person {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.roster-shift {
  margin-bottom: 4px;
}

.roster-actions {
  position: absolute;
  top: 4px;
  right: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.roster-card:hover .roster-actions {
  opacity: 1;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #c0c4cc;
}

.no-data-text {
  display: block;
  margin-bottom: 8px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.mt-2 {
  margin-top: 20px;
}

.operation-card {
  margin-bottom: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .week-calendar {
    overflow-x: auto;
  }

  .week-calendar-header,
  .week-calendar-body {
    min-width: 800px;
  }
}
</style>